package com.DFB.common.interceptor;

import com.DFB.common.Util.BaseContext;
import com.DFB.common.Util.JwtUtils;
import com.DFB.common.exception.TokenOverdueException;
import com.DFB.common.model.Result;
import com.DFB.common.model.ResultCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    /**
     * 通过拦截器 放行拦截器的某些请求 头部参数 add(未完成)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    //jwt校验
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1、从请求头中获取令牌
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null) {
            log.info("Authorization值为空");
            return false;
        }
        // 从第8个字符开始截取，去掉 "Bearer " 前缀
        String jwt = authorizationHeader.substring(7);
        //2、校验令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            response.getWriter().write(JSON.toJSONString(Result.error(ResultCode.USER_NOT_LOGGED_IN)));

            return false;
        }
        return false;
    }
}
